package com.sky.task;

import com.sky.entity.Orders;
import com.sky.enumeration.OrderStatus;
import com.sky.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.time.LocalDateTime;
import java.util.List;

public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Scheduled(cron = "0 0 1 * * ?")
    public void deliveryTimeout() {

        List<Orders> list = orderMapper.listByStatus(OrderStatus.DELIVERING.getValue());

        list.forEach(orders -> threadPoolTaskExecutor.execute(() -> orderMapper.update(

                Orders.builder()
                        .id(orders.getId())
                        .deliveryTime(LocalDateTime.now())
                        .build()
        )));
    }

    @Scheduled(cron = "0 0/15 * * * ?")
    public void payTimeout() {

        List<Orders> list = orderMapper.listByStatus(OrderStatus.WAIT_PAY.getValue());

        list.forEach(orders -> threadPoolTaskExecutor.execute(() -> orderMapper.update(

                Orders.builder()
                        .id(orders.getId())                             // 订单id
                        .status(OrderStatus.CANCEL.getValue())                          // 订单状态
                        .cancelTime(LocalDateTime.now())            // 取消时间
                        .cancelReason("订单支付超时")                 // 取消原因
                        .build()
        )));
    }
}
